<?php
/**
 * Plugin Name: Vireo Post Assistant
 * Plugin URI: https://zmqiang.com
 * Description: 基于DeepSeek API的智能文章助手
 * Version: 1.0.0
 * Author: 智码强哥
 * Author URI: https://zmqiang.com
 */

defined('ABSPATH') || exit;

class Vireo_Post_Assistant {
    private static $instance = null;

    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        // 添加菜单
        add_action('admin_menu', [$this, 'add_admin_menu']);
        // 注册设置
        add_action('admin_init', [$this, 'register_settings']);
        // 添加文章编辑页面的元框
        add_action('add_meta_boxes', [$this, 'add_meta_boxes']);
        // 添加AJAX处理
        add_action('wp_ajax_generate_post_content', [$this, 'ajax_generate_post_content']);
        add_action('wp_ajax_generate_post_titles', [$this, 'ajax_generate_post_titles']);
        // 在编辑页面加载古腾堡相关脚本
        add_action('enqueue_block_editor_assets', [$this, 'enqueue_block_editor_assets']);
        // 在编辑页面加载必要的脚本
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_scripts']);
    }

    public function add_admin_menu() {
        add_options_page(
            '文章助手设置',
            '文章助手',
            'manage_options',
            'vireo-post-assistant',
            [$this, 'render_settings_page']
        );
    }

    public function register_settings() {
        register_setting('vireo_post_assistant', 'vpa_settings', [
            'sanitize_callback' => [$this, 'sanitize_settings']
        ]);
        
        // API设置部分
        add_settings_section(
            'vpa_section_api',
            'API设置',
            null,
            'vireo-post-assistant'
        );

        // API地址
        add_settings_field(
            'deepseek_api_url',
            'DeepSeek API地址',
            [$this, 'render_text_field'],
            'vireo-post-assistant',
            'vpa_section_api',
            [
                'field' => 'deepseek_api_url',
                'default' => 'https://api.deepseek.com/v1/chat/completions',
                'description' => '默认为：https://api.deepseek.com/v1/chat/completions'
            ]
        );

        // API密钥
        add_settings_field(
            'deepseek_api_key',
            'DeepSeek API Key',
            [$this, 'render_text_field'],
            'vireo-post-assistant',
            'vpa_section_api',
            [
                'field' => 'deepseek_api_key',
                'description' => '请输入您的DeepSeek API密钥'
            ]
        );

        // 添加超时设置
        add_settings_field(
            'request_timeout',
            'API请求超时时间',
            [$this, 'render_number_field'],
            'vireo-post-assistant',
            'vpa_section_api',
            [
                'field' => 'request_timeout',
                'default' => '60',
                'min' => '10',
                'max' => '300',
                'step' => '1',
                'description' => '单位：秒。如果经常遇到超时错误，可以适当增加此值'
            ]
        );

        // 模型设置部分
        add_settings_section(
            'vpa_section_model',
            '模型设置',
            null,
            'vireo-post-assistant'
        );

        // 模型名称
        add_settings_field(
            'deepseek_model',
            '模型名称',
            [$this, 'render_text_field'],
            'vireo-post-assistant',
            'vpa_section_model',
            [
                'field' => 'deepseek_model',
                'default' => 'deepseek-chat',
                'description' => '例如：deepseek-chat, deepseek-coder'
            ]
        );

        // 温度设置
        add_settings_field(
            'temperature',
            '生成温度',
            [$this, 'render_number_field'],
            'vireo-post-assistant',
            'vpa_section_model',
            [
                'field' => 'temperature',
                'default' => '0.7',
                'min' => '0',
                'max' => '1',
                'step' => '0.1',
                'description' => '范围：0-1，值越大生成的内容越随机'
            ]
        );

        // 最大Token
        add_settings_field(
            'max_tokens',
            '最大Token数',
            [$this, 'render_number_field'],
            'vireo-post-assistant',
            'vpa_section_model',
            [
                'field' => 'max_tokens',
                'default' => '2000',
                'min' => '100',
                'max' => '8000',
                'step' => '100',
                'description' => '范围：100-8000，决定生成内容的最大长度'
            ]
        );
    }

    public function render_settings_page() {
        ?>
        <div class="wrap">
            <h1>文章助手设置</h1>
            <form method="post" action="options.php">
                <?php
                settings_fields('vireo_post_assistant');
                do_settings_sections('vireo-post-assistant');
                submit_button();
                ?>
            </form>
        </div>
        <?php
    }

    public function render_text_field($args) {
        $options = get_option('vpa_settings');
        $field = $args['field'];
        $value = isset($options[$field]) ? $options[$field] : ($args['default'] ?? '');
        ?>
        <input type="text" 
               name="vpa_settings[<?php echo esc_attr($field); ?>]" 
               value="<?php echo esc_attr($value); ?>" 
               class="regular-text">
        <?php if (!empty($args['description'])): ?>
            <p class="description"><?php echo esc_html($args['description']); ?></p>
        <?php endif;
    }

    public function render_number_field($args) {
        $options = get_option('vpa_settings');
        $field = $args['field'];
        $value = isset($options[$field]) ? $options[$field] : ($args['default'] ?? '');
        ?>
        <input type="number" 
               name="vpa_settings[<?php echo esc_attr($field); ?>]" 
               value="<?php echo esc_attr($value); ?>" 
               class="regular-text"
               min="<?php echo esc_attr($args['min']); ?>"
               max="<?php echo esc_attr($args['max']); ?>"
               step="<?php echo esc_attr($args['step']); ?>">
        <?php if (!empty($args['description'])): ?>
            <p class="description"><?php echo esc_html($args['description']); ?></p>
        <?php endif;
    }

    public function sanitize_settings($input) {
        $sanitized = [];
        
        // API URL
        $sanitized['deepseek_api_url'] = esc_url_raw($input['deepseek_api_url']);
        
        // API Key
        $sanitized['deepseek_api_key'] = sanitize_text_field($input['deepseek_api_key']);
        
        // 模型名称
        $sanitized['deepseek_model'] = sanitize_text_field($input['deepseek_model']);
        
        // 温度值
        $temperature = floatval($input['temperature']);
        $sanitized['temperature'] = min(max($temperature, 0), 1);
        
        // 最大Token
        $max_tokens = intval($input['max_tokens']);
        $sanitized['max_tokens'] = min(max($max_tokens, 100), 8000);
        
        // 超时设置
        $timeout = intval($input['request_timeout']);
        $sanitized['request_timeout'] = min(max($timeout, 10), 300);
        
        return $sanitized;
    }

    public function add_meta_boxes() {
        add_meta_box(
            'vireo_post_assistant_box',
            '文章助手',
            [$this, 'render_meta_box'],
            'post',
            'side',
            'high'
        );
    }

    public function render_meta_box($post) {
        wp_nonce_field('vireo_post_assistant_action', 'vireo_post_assistant_nonce');
        ?>
        <div class="vireo-post-assistant-box">
            <!-- 添加提示词输入框 -->
            <div class="prompt-input-section mb-3">
                <label for="title-prompt" class="block mb-2">输入提示词：</label>
                <textarea id="title-prompt" 
                          class="widefat" 
                          rows="3" 
                          placeholder="例如：写一篇关于WordPress优化的文章，重点介绍性能优化方面..."></textarea>
            </div>

            <p>
                <button type="button" class="button button-primary w-full" id="generate-titles">
                    <i class="dashicons dashicons-edit"></i> 生成推荐标题
                </button>
            </p>

            <div id="suggested-titles" class="hidden">
                <div class="flex justify-between items-center mb-2">
                    <h4 class="m-0">推荐标题：</h4>
                    <button type="button" class="button button-secondary" id="refresh-titles">
                        <i class="dashicons dashicons-update"></i> 换一批
                    </button>
                </div>
                <ul class="titles-list"></ul>
            </div>

            <div class="content-generation-section mt-3">
                <button type="button" class="button button-primary w-full" id="generate-content">
                    <i class="dashicons dashicons-welcome-write-blog"></i> 生成文章内容
                </button>
                <div id="generation-status" class="mt-2"></div>
            </div>
        </div>

        <style>
        #vireo_post_assistant_box {
            margin-top: 0 !important;
            order: -1; /* 确保显示在最前面 */
        }

        #vireo_post_assistant_box .inside {
            padding: 0;
            margin: 0;
        }

        #vireo_post_assistant_box .hndle {
            cursor: default;
            padding: 12px;
            background: #f5f5f5;
            border-bottom: 1px solid #e5e5e5;
        }

        #vireo_post_assistant_box .hndle:hover {
            background: #f5f5f5;
        }

        #vireo_post_assistant_box .vireo-post-assistant-box {
            padding: 12px;
        }
        .vireo-post-assistant-box {
            margin-bottom: 1em;
            padding: 10px;
            background: #fff;
            border: 1px solid #e5e5e5;
            box-shadow: 0 1px 1px rgba(0,0,0,.04);
        }
        .vireo-post-assistant-box .hidden {
            display: none;
        }
        .vireo-post-assistant-box .mb-2 {
            margin-bottom: 0.5em;
        }
        .vireo-post-assistant-box .mb-3 {
            margin-bottom: 1em;
        }
        .vireo-post-assistant-box .mt-2 {
            margin-top: 0.5em;
        }
        .vireo-post-assistant-box .mt-3 {
            margin-top: 1em;
        }
        .vireo-post-assistant-box .w-full {
            width: 100%;
        }
        .vireo-post-assistant-box .block {
            display: block;
        }
        .titles-list {
            margin: 0.5em 0;
            padding-left: 1.5em;
            list-style: decimal;
        }
        .titles-list li {
            margin: 0.5em 0;
            cursor: pointer;
            padding: 0.3em 0.5em;
            border-radius: 3px;
            transition: background-color 0.2s;
        }
        .titles-list li:hover {
            background-color: #f0f0f0;
        }
        #generation-status {
            margin-top: 10px;
            padding: 8px;
            border-radius: 3px;
            background-color: #f5f5f5;
            color: #666;
            font-size: 13px;
        }
        #generation-status .spinner {
            float: none;
            margin: 0 5px 0 0;
            vertical-align: middle;
        }
        #generation-status .dashicons {
            vertical-align: middle;
            margin-right: 5px;
        }
        #generation-status .dashicons-yes {
            color: #46b450;
        }
        #generation-status .dashicons-no {
            color: #dc3232;
        }
        .button .dashicons {
            margin-top: 4px;
            margin-right: 4px;
        }
        .flex {
            display: flex;
        }
        .justify-between {
            justify-content: space-between;
        }
        .items-center {
            align-items: center;
        }
        .m-0 {
            margin: 0;
        }
        #refresh-titles {
            padding: 0 8px;
            height: 24px;
            line-height: 22px;
        }
        #refresh-titles .dashicons {
            width: 16px;
            height: 16px;
            font-size: 16px;
            margin: 3px 0 0 0;
        }
        .titles-list li {
            position: relative;
            padding-right: 25px;
        }
        .titles-list li:after {
            content: '\f345';
            font-family: dashicons;
            position: absolute;
            right: 5px;
            top: 50%;
            transform: translateY(-50%);
            opacity: 0;
            transition: opacity 0.2s;
        }
        .titles-list li:hover:after {
            opacity: 1;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .spin {
            animation: spin 1s linear infinite;
        }
        </style>

        <script>
        jQuery(document).ready(function($) {
            const ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
            let lastPrompt = '';
            
            function generateTitles(prompt, button) {
                button.prop('disabled', true);
                lastPrompt = prompt;
                
                // 添加生成中的状态提示
                $('#suggested-titles').addClass('hidden');
                $('#generation-status').html('<span class="spinner is-active"></span> 正在生成标题...');
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'generate_post_titles',
                        nonce: $('#vireo_post_assistant_nonce').val(),
                        post_id: $('#post_ID').val(),
                        prompt: prompt
                    },
                    success: function(response) {
                        if (response.success) {
                            const titlesList = $('#suggested-titles ul');
                            titlesList.empty();
                            response.data.titles.forEach(function(title) {
                                titlesList.append(`
                                    <li class="use-title">
                                        ${title}
                                    </li>
                                `);
                            });
                            $('#suggested-titles').removeClass('hidden');
                            $('#generation-status').html('<span class="dashicons dashicons-yes"></span> 标题生成完成！');
                        } else {
                            $('#generation-status').html('<span class="dashicons dashicons-no"></span> ' + response.data.message);
                        }
                    },
                    error: function() {
                        $('#generation-status').html('<span class="dashicons dashicons-no"></span> 生成标题失败，请重试');
                    },
                    complete: function() {
                        button.prop('disabled', false);
                    }
                });
            }

            // 生成标题
            $('#generate-titles').click(function() {
                const prompt = $('#title-prompt').val();
                
                if (!prompt.trim()) {
                    alert('请输入提示词');
                    return;
                }

                generateTitles(prompt, $(this));
            });

            // 换一批标题
            $('#refresh-titles').click(function() {
                if (!lastPrompt.trim()) {
                    alert('请先输入提示词');
                    return;
                }

                const button = $(this);
                button.find('.dashicons').addClass('spin');
                generateTitles(lastPrompt, button);
            });

            // 修改使用选中的标题的处理逻辑
            $(document).on('click', '.use-title', function(e) {
                e.preventDefault();
                const title = $(this).text().trim();
                
                // 支持古腾堡编辑器
                if (wp.data && wp.data.select('core/editor')) {
                    wp.data.dispatch('core/editor').editPost({ title: title });
                } else {
                    // 传统编辑器支持
                    $('#title').val(title);
                }

                // 添加视觉反馈
                const originalBg = $(this).css('background-color');
                $(this)
                    .css('background-color', '#e0f0e0')
                    .delay(500)
                    .queue(function(next) {
                        $(this).css('background-color', originalBg);
                        next();
                    });
            });

            // 修改生成内容的处理逻辑
            $('#generate-content').click(function() {
                const button = $(this);
                let title = '';

                // 获取标题（支持古腾堡和传统编辑器）
                if (wp.data && wp.data.select('core/editor')) {
                    title = wp.data.select('core/editor').getEditedPostAttribute('title');
                } else {
                    title = $('#title').val().trim();
                }
                
                if (!title) {
                    alert('请先选择或输入文章标题');
                    return;
                }

                button.prop('disabled', true);
                $('#generation-status').html('<span class="spinner is-active"></span> 正在生成内容...');
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'generate_post_content',
                        nonce: $('#vireo_post_assistant_nonce').val(),
                        post_id: $('#post_ID').val(),
                        title: title
                    },
                    success: function(response) {
                        if (response.success) {
                            const blocks = response.data.blocks;
                            
                            // 支持古腾堡编辑器
                            if (wp.data && wp.data.select('core/editor')) {
                                // 插入所有区块
                                blocks.forEach(block => {
                                    wp.data.dispatch('core/block-editor').insertBlocks(
                                        wp.blocks.createBlock(block.blockName, block.attrs)
                                    );
                                });
                                $('#generation-status').html('<span class="dashicons dashicons-yes"></span> 内容生成完成！');
                            } else {
                                $('#generation-status').html('<span class="dashicons dashicons-no"></span> 仅支持古腾堡编辑器');
                            }
                        } else {
                            $('#generation-status').html('<span class="dashicons dashicons-no"></span> ' + response.data.message);
                        }
                    },
                    error: function() {
                        $('#generation-status').html('<span class="dashicons dashicons-no"></span> 生成失败，请重试');
                    },
                    complete: function() {
                        button.prop('disabled', false);
                    }
                });
            });
        });
        </script>
        <?php
    }

    public function ajax_generate_post_titles() {
        check_ajax_referer('vireo_post_assistant_action', 'nonce');
        
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(['message' => '权限不足']);
        }

        $post_id = intval($_POST['post_id']);
        $post = get_post($post_id);
        
        try {
            $titles = $this->generate_titles($post);
            wp_send_json_success(['titles' => $titles]);
        } catch (Exception $e) {
            wp_send_json_error(['message' => $e->getMessage()]);
        }
    }

    public function ajax_generate_post_content() {
        check_ajax_referer('vireo_post_assistant_action', 'nonce');
        
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(['message' => '权限不足']);
        }

        $post_id = intval($_POST['post_id']);
        $post = get_post($post_id);
        
        try {
            $blocks = $this->generate_content($post);
            wp_send_json_success(['blocks' => $blocks]);
        } catch (Exception $e) {
            wp_send_json_error(['message' => $e->getMessage()]);
        }
    }

    private function make_api_request($url, $options, $max_retries = 3) {
        $attempt = 0;
        $timeout = intval($options['request_timeout'] ?? 60);
        
        while ($attempt < $max_retries) {
            $response = wp_remote_post($url, [
                'headers' => [
                    'Authorization' => 'Bearer ' . $options['deepseek_api_key'],
                    'Content-Type' => 'application/json'
                ],
                'body' => $options['body'],
                'timeout' => $timeout,
                'sslverify' => false
            ]);

            // 如果请求成功，直接返回
            if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
                return $response;
            }

            // 如果是超时错误，增加超时时间并重试
            $attempt++;
            if ($attempt < $max_retries) {
                $timeout += 30; // 每次重试增加30秒超时时间
                sleep(2); // 等待2秒后重试
            }
        }

        // 所有重试都失败后返回最后一次的响应
        return $response;
    }

    private function generate_titles($post) {
        $options = get_option('vpa_settings');
        
        if (empty($options['deepseek_api_key'])) {
            throw new Exception('请先设置 DeepSeek API Key');
        }

        $prompt = isset($_POST['prompt']) ? sanitize_textarea_field($_POST['prompt']) : '';
        if (empty($prompt)) {
            throw new Exception('请提供提示词');
        }

        $api_prompt = "根据以下提示词生成5个吸引人的文章标题，要求：\n";
        $api_prompt .= "1. 标题要简洁有力\n";
        $api_prompt .= "2. 包含关键词\n";
        $api_prompt .= "3. 符合SEO优化原则\n";
        $api_prompt .= "4. 吸引读者点击\n";
        $api_prompt .= "5. 直接输出纯文本标题，不要使用任何Markdown格式\n";
        $api_prompt .= "6. 每个标题单独一行\n";
        $api_prompt .= "7. 不要添加任何序号或符号\n\n";
        $api_prompt .= "提示词：" . $prompt;

        $api_url = $options['deepseek_api_url'] ?: 'https://api.deepseek.com/v1/chat/completions';

        $request_options = [
            'deepseek_api_key' => $options['deepseek_api_key'],
            'request_timeout' => $options['request_timeout'] ?? 60,
            'body' => json_encode([
                'model' => $options['deepseek_model'] ?: 'deepseek-chat',
                'messages' => [
                    ['role' => 'user', 'content' => $api_prompt]
                ],
                'temperature' => floatval($options['temperature'] ?: 0.7),
                'max_tokens' => intval($options['max_tokens'] ?: 8000)
            ])
        ];

        $response = $this->make_api_request($api_url, $request_options);

        if (is_wp_error($response)) {
            throw new Exception('API请求失败：' . $response->get_error_message() . 
                              '。请检查网络连接或增加超时时间。');
        }

        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            throw new Exception('API响应错误，状态码：' . $response_code . 
                              '。如果问题持续存在，请联系管理员。');
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        if (empty($body['choices'][0]['message']['content'])) {
            throw new Exception('API返回数据无效。请重试或联系管理员。');
        }

        $content = $body['choices'][0]['message']['content'];
        
        // 处理返回的内容
        $titles = array_filter(array_map('trim', explode("\n", $content)));
        
        // 过滤掉空行和不符合要求的行
        $titles = array_values(array_filter($titles, function($title) {
            return !empty($title) && 
                   strlen($title) > 5 && 
                   !preg_match('/^[#*-]/', $title); // 过滤掉Markdown符号
        }));
        
        // 如果标题数量超过5个，只取前5个
        return array_slice($titles, 0, 5);
    }

    private function generate_content($post) {
        $options = get_option('vpa_settings');
        
        if (empty($options['deepseek_api_key'])) {
            throw new Exception('请先设置 DeepSeek API Key');
        }

        $api_url = $options['deepseek_api_url'] ?: 'https://api.deepseek.com/v1/chat/completions';
        
        $prompt = "请根据以下标题生成一篇高质量的文章，要求：\n";
        $prompt .= "1. 内容要专业、准确\n";
        $prompt .= "2. 结构要清晰，内容要详细\n";
        $prompt .= "3. 使用Markdown格式输出\n";
        $prompt .= "4. 不要使用任何解释\n";
        $prompt .= "5. 不要返回标题\n";
        $prompt .= "标题：" . $post->post_title;

        $request_options = [
            'deepseek_api_key' => $options['deepseek_api_key'],
            'request_timeout' => $options['request_timeout'] ?? 60,
            'body' => json_encode([
                'model' => $options['deepseek_model'] ?: 'deepseek-chat',
                'messages' => [
                    ['role' => 'user', 'content' => $prompt]
                ],
                'temperature' => floatval($options['temperature'] ?: 0.7),
                'max_tokens' => intval($options['max_tokens'] ?: 2000)
            ])
        ];

        $response = $this->make_api_request($api_url, $request_options);

        if (is_wp_error($response)) {
            throw new Exception('API请求失败：' . $response->get_error_message() . 
                              '。请检查网络连接或增加超时时间。');
        }

        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            throw new Exception('API响应错误，状态码：' . $response_code . 
                              '。如果问题持续存在，请联系管理员。');
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        if (empty($body['choices'][0]['message']['content'])) {
            throw new Exception('API返回数据无效。请重试或联系管理员。');
        }

        // 获取生成的内容并清理
        $content = $body['choices'][0]['message']['content'];
        
        // 清理多余的符号
        $content = $this->clean_content($content);
        
        // 调试：输出API返回的内容
        error_log('API返回的内容：' . $content);
        
        // 将Markdown转换为古腾堡区块
        $blocks = $this->convert_markdown_to_blocks($content);
        
        return $blocks;
    }

    // 新增清理内容的函数
    private function clean_content($content) {
        // 去掉多余的 `·` 符号
        $content = str_replace('`markdown', '', $content);
        
        // 去掉结尾的 `。` 符号
        $content = rtrim($content, '`');
        
        return $content;
    }

    // 新增Markdown转古腾堡区块的函数
    private function convert_markdown_to_blocks($markdown) {
        $blocks = [];
        
        // 按空行分割内容
        $paragraphs = preg_split('/\n\s*\n/', $markdown);
        
        foreach ($paragraphs as $paragraph) {
            $paragraph = trim($paragraph);
            if (empty($paragraph)) {
                continue;
            }
            
            // 判断段落类型并转换为相应的区块
            if (preg_match('/^#\s+(.*)/', $paragraph, $matches)) {
                // 一级标题
                $blocks[] = [
                    'blockName' => 'core/heading',
                    'attrs' => [
                        'level' => 1,
                        'content' => $this->convert_font_styles($matches[1])
                    ]
                ];
            } elseif (preg_match('/^##\s+(.*)/', $paragraph, $matches)) {
                // 二级标题
                $blocks[] = [
                    'blockName' => 'core/heading',
                    'attrs' => [
                        'level' => 2,
                        'content' => $this->convert_font_styles($matches[1])
                    ]
                ];
            } elseif (preg_match('/^###\s+(.*)/', $paragraph, $matches)) {
                // 三级标题
                $blocks[] = [
                    'blockName' => 'core/heading',
                    'attrs' => [
                        'level' => 3,
                        'content' => $this->convert_font_styles($matches[1])
                    ]
                ];
            } elseif (preg_match('/^####\s+(.*)/', $paragraph, $matches)) {
                // 四级标题
                $blocks[] = [
                    'blockName' => 'core/heading',
                    'attrs' => [
                        'level' => 4,
                        'content' => $this->convert_font_styles($matches[1])
                    ]
                ];
            } elseif (preg_match('/^#####\s+(.*)/', $paragraph, $matches)) {
                // 五级标题
                $blocks[] = [
                    'blockName' => 'core/heading',
                    'attrs' => [
                        'level' => 5,
                        'content' => $this->convert_font_styles($matches[1])
                    ]
                ];
            } elseif (preg_match('/^######\s+(.*)/', $paragraph, $matches)) {
                // 六级标题
                $blocks[] = [
                    'blockName' => 'core/heading',
                    'attrs' => [
                        'level' => 6,
                        'content' => $this->convert_font_styles($matches[1])
                    ]
                ];
            } elseif (preg_match('/^\*\s+(.*)/', $paragraph, $matches)) {
                // 列表项
                $items = explode("\n", $paragraph);
                $list_items = [];
                foreach ($items as $item) {
                    if (preg_match('/^\*\s+(.*)/', $item, $item_matches)) {
                        $list_items[] = $this->convert_font_styles($item_matches[1]);
                    }
                }
                $blocks[] = [
                    'blockName' => 'core/list',
                    'attrs' => [
                        'values' => $list_items
                    ]
                ];
            } elseif (preg_match('/^```(.*)\n([\s\S]*?)```/m', $paragraph, $matches)) {
                // 代码块
                $blocks[] = [
                    'blockName' => 'core/code',
                    'attrs' => [
                        'content' => $matches[2]
                    ]
                ];
            } else {
                // 普通段落
                $blocks[] = [
                    'blockName' => 'core/paragraph',
                    'attrs' => [
                        'content' => $this->convert_font_styles($paragraph)
                    ]
                ];
            }
        }
        
        // 调试：输出转换后的区块
        error_log('转换后的区块：' . print_r($blocks, true));
        
        return $blocks;
    }

    // 新增字体样式转换函数
    private function convert_font_styles($text) {
        // 转换加粗 **text** 或 __text__
        $text = preg_replace('/\*\*(.*?)\*\*/', '<strong>$1</strong>', $text);
        $text = preg_replace('/__(.*?)__/', '<strong>$1</strong>', $text);
        
        // 转换斜体 *text* 或 _text_
        $text = preg_replace('/\*(.*?)\*/', '<em>$1</em>', $text);
        $text = preg_replace('/_(.*?)_/', '<em>$1</em>', $text);
        
        // 转换删除线 ~~text~~
        $text = preg_replace('/~~(.*?)~~/', '<del>$1</del>', $text);
        
        // 转换行内代码 `code`
        $text = preg_replace('/`(.*?)`/', '<code>$1</code>', $text);
        
        // 转换链接 [text](url)
        $text = preg_replace('/\[(.*?)\]\((.*?)\)/', '<a href="$2">$1</a>', $text);
        
        // 转换图片 ![alt](url)
        $text = preg_replace('/!\[(.*?)\]\((.*?)\)/', '<img src="$2" alt="$1">', $text);
        
        return $text;
    }

    public function enqueue_block_editor_assets() {
        // 确保在古腾堡编辑器中加载必要的脚本
        wp_enqueue_script(
            'vireo-post-assistant-gutenberg',
            plugins_url('js/gutenberg.js', __FILE__),
            ['wp-blocks', 'wp-element', 'wp-editor', 'wp-components', 'wp-data'],
            '1.0.0',
            true
        );
    }

    public function enqueue_admin_scripts($hook) {
        if (!in_array($hook, ['post.php', 'post-new.php'])) {
            return;
        }

       
    }
}

// 初始化插件
add_action('plugins_loaded', function() {
    Vireo_Post_Assistant::get_instance();
}); 